<template>
  <view class="min-h-[100vh]">
    <!-- 导航栏 -->
    <view class="backdrop-blur-sm sticky top-0 z-[99]">
      <up-navbar placeholder bgColor="transparent">
        <template #left>
          <view class="w-[64rpx] h-[64rpx]">
            <up-image
              :src="logo"
              width="64rpx"
              height="64rpx"
              :showMenuByLongpress="false"
              bgColor="transparent"></up-image>
          </view>
        </template>
        <template #center>
          <view class="w-[440rpx] h-[64rpx]">
            <up-search
              @search="resetGoods"
              placeholder="搜索商品"
              v-model="params.key"
              bgColor="rgba(255, 255, 255, 0.05)"
              :inputStyle="{ backgroundColor: 'transparent' }"
              color="#fff"
              :showAction="false"></up-search>
          </view>
        </template>
      </up-navbar>
    </view>
    <!-- 轮播图 -->
    <view class="w-full h-[408rpx] relative">
      <up-swiper
        :list="$url(banner)"
        height="408rpx"
        :loading="isLoading"
        keyName="url"
        bgColor="#000"></up-swiper>
      <view class="gradient absolute top-0 left-0 w-full h-[408rpx]"></view>
    </view>
    <!-- 通知 -->
    <view class="px-[20rpx] pt-[16rpx] pb-[24rpx]">
      <view
        class="p-[6rpx] pr-[24rpx] rounded-[8rpx] border border-[#B51A26] overflow-hidden notice flex items-center">
        <up-image
          :src="noticeIcon"
          width="56rpx"
          height="44rpx"
          class="z-10 flex-shrink-0"
          :showMenuByLongpress="false"
          bgColor="transparent"></up-image>
        <view class="flex-1 ml-[24rpx] overflow-hidden">
          <view
            class="flex items-center gap-[100rpx] whitespace-nowrap notice-text">
            <view
              class="flex items-center"
              v-for="item in notice"
              :key="item.id">
              <text
                class="text-[24rpx] text-white font-bold"
                v-for="(item, index) in innerText(item.content)"
                :key="index"
                >{{ item }}</text
              >
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 金刚区 -->
    <view class="px-[20rpx] grid grid-cols-2 gap-[18rpx]">
      <view
        class="relative"
        @click="utils.useRouter('/goods_packages/bonus/bonus')">
        <up-image
          bgColor="transparent"
          width="100%"
          :src="bonus"
          mode="widthFix"
          :showMenuByLongpress="false"></up-image>
        <up-image
          class="absolute bottom-0 -right-[14rpx]"
          bgColor="transparent"
          width="180rpx"
          :src="GUNDAM_B"
          mode="widthFix"
          :showMenuByLongpress="false"></up-image>
      </view>
      <view
        class="relative"
        @click="utils.useRouter('/goods_packages/invite/invite')">
        <up-image
          bgColor="transparent"
          width="100%"
          :src="friend"
          :webp="false"
          mode="widthFix"
          :showMenuByLongpress="false"></up-image>
        <up-image
          class="absolute bottom-0 -right-[14rpx]"
          bgColor="transparent"
          width="180rpx"
          :src="GUNDAM_F"
          :webp="false"
          mode="widthFix"
          :showMenuByLongpress="false"></up-image>
      </view>
    </view>
    <!-- 分类 -->
    <TabsView :list="classfyList" @classfyChange="classfyChange"></TabsView>
    <!-- 商品列表 -->
    <view class="px-[20rpx]">
      <GoodsList :goods="goods" @click="goodsClick"></GoodsList>
    </view>
    <!-- 背景 -->
    <BackgroundImage />
    <!-- 底部导航栏 -->
    <CustomTabbar :currentIndex="0" />
  </view>
</template>

<script setup>
import { ref, reactive, computed, watch } from "vue";
import utils from "@/utils/utils";
import logo from "@/static/images/common/logo.png";
import noticeIcon from "@/static/images/index/notice.png"; // 通知
import friend from "@/static/images/index/friend.png"; // 好友
import bonus from "@/static/images/index/bonus.png"; // 奖励
import GUNDAM_B from "@/static/images/index/GUNDAM_B.png"; //高达
import GUNDAM_F from "@/static/images/index/GUNDAM_F.png"; //高达
import useClassfy from "@/hooks/useClassfy.js";
import GoodsList from "@/components/GoodsList.vue";
import {
  onPullDownRefresh,
  onReachBottom,
  onLoad,
  onShow,
} from "@dcloudio/uni-app";
import { getHomeData, getGoodsList } from "@/api/index.js";
onLoad((options) => {
  if (options.scene) {
    uni.setStorageSync("inviteId", options.scene);
  }
  getIndexData(); // 获取首页数据
  resetGoods(); // 获取商品列表
});
onShow(() => {
  if (uni.getStorageSync("isUpdate")) {
    getIndexData(); // 获取首页数据
    resetGoods(); // 获取商品列表
    uni.removeStorageSync("isUpdate");
  }
});
onPullDownRefresh(() => {
  Promise.all([getIndexData(), resetGoods()]).finally(() => {
    uni.stopPullDownRefresh();
  });
});
onReachBottom(() => {
  if (goods.value.length < params.total) {
    params.pageNum++;
    getGoods();
  }
});
const { banner, isLoading } = useSwiper(); // 轮播图
const { notice, innerText } = useNotice(); // 通知
const { classfyList, currentIndex, classfyChange } = useClassfy(); // 分类
const { goods, getGoods, resetGoods, params, goodsClick } = useGoods(); // 商品
/**
 * @description 轮播图
 * @returns {Array} 轮播图
 * @returns {Boolean} 轮播图是否加载中
 */
function useSwiper() {
  const banner = ref([]);
  const isLoading = ref(false); // 轮播图是否加载中
  return {
    banner,
    isLoading,
  };
}
/**
 * @description 通知
 * @returns {String} 通知
 * @returns {Array} 拆分后的数组
 */
function useNotice() {
  const notice = ref("");
  /**
   * @description 拆分字符串
   * @param {string} notice 通知数组
   * @returns {Array} 拆分后的数组
   */
  const innerText = (notice) => {
    if (!notice) return [];
    let result = [],
      // 每组text标签的字符长度
      len = 20;
    const textArr = notice.split("");
    for (let i = 0; i < textArr.length; i += len) {
      // 对拆分的后的text进行slice分割，得到的为数组再进行join拼接为字符串
      result.push(textArr.slice(i, i + len).join(""));
    }
    return result;
  };
  return {
    notice,
    innerText,
  };
}
/**
 * @description 商品
 * @returns {Array} goods 商品
 * @returns {Function} getGoods 获取商品
 * @returns {Function} resetGoods 重置商品
 * @returns {Function} goodsClick 商品点击事件
 * @returns {Object} params 参数
 */
function useGoods() {
  const params = reactive({
    pageNum: 1,
    pageSize: 6,
    type: "",
    tag: "",
    total: 0,
    key: "",
  });
  const goods = ref([]);
  /**
   * @description 获取商品
   * @function
   * @async
   */
  const getGoods = async () => {
    try {
      const res = await getGoodsList(params);
      goods.value = goods.value.concat(
        res.rows.map((item, index) => {
          return {
            ...item,
            animationDelay: index * 0.2 + "s",
          };
        })
      );
      params.total = res.total;
    } catch (error) {}
  };
  const resetGoods = () => {
    goods.value = [];
    params.pageNum = 1;
    getGoods();
  };
  const goodsClick = (item) => {
    if (item.tag == 2) {
      utils.useRouter(
        `/goods_packages/points_rewards/points_rewards?prizeId=${item.id}`
      );
      return;
    }
    const routerMap = {
      0: "/goods_packages/reward/reward",
      2: "/goods_packages/arena_reward/arena_reward",
      3: "/goods_packages/arena_reward/arena_reward",
      1: "/goods_packages/unlimited_rewards/unlimited_rewards",
      4: "/goods_packages/demonlord_rewards/demonlord_rewards",
    };
    utils.useRouter(`${routerMap[item.type]}?prizeId=${item.id}`);
  };
  return {
    goods,
    getGoods,
    resetGoods,
    goodsClick,
    params,
  };
}
/**
 * @description 获取首页数据
 */
const getIndexData = async () => {
  try {
    isLoading.value = true;
    const res = await getHomeData();
    isLoading.value = false;
    banner.value = res.data.brannList.map((item) => {
      return {
        ...item,
        url: item.pic,
      };
    });
    notice.value = res.data.noticeList;
    classfyList.value = [
      {
        type: "",
        name: "全部",
      },
      ...res.data.typeList,
    ];
  } catch (error) {}
};
/**
 * @description 监听分类切换
 */
watch(currentIndex, (newIndex) => {
  params.type = classfyList.value[newIndex].type;
  resetGoods();
});
</script>

<style lang="scss" scoped>
:deep(.u-navbar__content) {
  justify-content: space-between !important;
  padding-left: 100rpx;
}
/* 渐变 */
.gradient {
  background: linear-gradient(
      to bottom,
      #190808 0%,
      transparent 64rpx,
      transparent 100%
    ),
    linear-gradient(to right, #190808 0%, transparent 64rpx, transparent 100%),
    linear-gradient(to left, #190808 0%, transparent 64rpx, transparent 100%),
    linear-gradient(to top, #190808 0%, transparent 64rpx, transparent 100%);
}
/* 渐变notice */
.notice {
  background: linear-gradient(180deg, rgba(148, 18, 29, 0) 41%, #94121d 100%);
}
.notice-text {
  padding-left: 100%;
  word-break: keep-all;
  white-space: nowrap;
  animation: u-loop-animation 10s linear infinite both;
}
/* notice动画 */
@keyframes u-loop-animation {
  0% {
    transform: translate3d(0, 0, 0);
  }
  100% {
    transform: translate3d(-200%, 0, 0);
  }
}
</style>
